package edu.taru.office.controller;

import edu.taru.office.common.Constants;
import edu.taru.office.pojo.Dept;
import edu.taru.office.pojo.Leave;

import edu.taru.office.pojo.User;
import edu.taru.office.service.DeptService;
import edu.taru.office.service.LeaveService;
import edu.taru.office.service.ProcessService;

import edu.taru.office.util.UserUtil;
import edu.taru.office.vo.MyComment;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chudu on 2018/5/5.
 * 请假申请业务
 */
@Controller
@RequestMapping("/leave")
public class LeaveProcessController {
    private Logger logger= LoggerFactory.getLogger(TravelProcessController.class);

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
   /* @Autowired
    private RepositoryService repositoryService;*/

    @Autowired
    private HistoryService historyService;

   /* @Autowired
    private ProcessService processService;*/
    @Autowired
    private LeaveService leaveService;
    @Autowired
    private DeptService deptService;


    /**
     *进入请假申请页面
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/process/apply")
    public String  apply(HttpSession session, Model model){
        String uid = UserUtil.getSessionUserFromSession(session).getUserid();
        Dept dept =deptService.selectMyDept(uid);
        model.addAttribute("dept",dept);
        return "process/leave-apply";
    }

    /**
     * 2、提交申请（启动审批流程,向业务表中插入数据）
     * @param leave
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/process/submit")
    public String  submit(Leave leave, Model model, HttpSession session){
        User user = UserUtil.getUserFromSession(session);
        leave.setUname(user.getName());
        leave.setUid(Long.valueOf(user.getId()));
        //插入业务表
        leaveService.insert(leave);
        Map<String, Object> variables =new HashMap<>();
        String businessKey  =leave.getId().toString();
        logger.info("----------------------businessKey:"+businessKey);
        variables.put(Constants.Process.BUSINESS_KEY,businessKey);
        variables.put(Constants.Process.CATEGORY,"leave");//一定要和路径统一
        variables.put(Constants.Process.TITLE,leave.getTitle());//
        variables.put(Constants.Process.OWNER,user.getName());//
        //把借款存储到流程变量中 ,因为不属于公共变量，属于业务变量，所以不需要在常量中设置
        variables.put("days",leave.getDays());
        Authentication.setAuthenticatedUserId(String.valueOf(user.getId()));//  启动人
        ProcessInstance processInstance =runtimeService.startProcessInstanceByKey("myProcess_1",businessKey,variables);
        model.addAttribute("message","已经启动审批流程-"+processInstance.getId()+",请假编号"+businessKey);
        return "process/submit-success";
    }

    /**
     * 3、根据任务编号和审批的类型，进入具体的审计页面,查看审批意见
     * @param taskId
     * @param busId
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/process/audit")
    public String  audit(
            @RequestParam("taskId") String taskId ,
            @RequestParam("busId") String busId,
            Model model , HttpSession session){

        //查询业务
        Leave leave = leaveService.selectLeave(busId);

        List<MyComment> historyCommnets = new ArrayList<MyComment>();
//         1) 获取流程实例的ID
        Task task = this.taskService.createTaskQuery().taskId(taskId).singleResult();
        ProcessInstance pi =runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
//       2）通过流程实例查询所有的(用户任务类型)历史活动
        List<HistoricActivityInstance> hais = historyService.createHistoricActivityInstanceQuery().processInstanceId(pi.getId()).activityType("userTask").list();
//       3）查询每个历史任务的批注
        if(hais!=null && hais.size()>=0){
            for (HistoricActivityInstance hai : hais) {
                String historytaskId = hai.getTaskId();
                List<Comment> comments = taskService.getTaskComments(historytaskId);
                // 4）如果当前任务有批注信息，添加到集合中
                if(comments!=null && comments.size()>0){
                    for(Comment c:comments){
                        MyComment  myComment =new MyComment();
                        myComment.setContent(c.getFullMessage());
                        logger.info("----------------------audit  message is  {} and leader  is",c.getFullMessage(),c.getUserId());
                        myComment.setName(c.getUserId());
                        historyCommnets.add(myComment);
                    }

                }
            }

        }
        model.addAttribute("comments",historyCommnets);
        model.addAttribute("leave",leave);
        model.addAttribute("taskId",taskId);
        model.addAttribute("processId",pi.getId());  //travle表中已经绑定，但是忘记了
        return  "process/leave-audit";
    }

    /**
     * 4、审批提交（填写意见，）
     * @param model
     * @param id
     * @param processId
     * @param taskId
     * @param comment
     * @param session
     * @return
     */
    @RequestMapping("/process/complete")
    public String  complete(Model model ,String id, String processId,  String taskId, String  comment, HttpSession session){

        User user =UserUtil.getUserFromSession(session);
        // 由于流程用户上下文对象是线程独立的，所以要在需要的位置设置，要保证设置和获取操作在同一个线程中
        Authentication.setAuthenticatedUserId(user.getName());//批注人的名称  一定要写，不然查看的时候不知道人物信息
        // 添加批注信息
        taskService.addComment(taskId, null, "approved".equals(comment)?"同意":"不同意");//comment为批注内容
        Map<String, Object> taskVariables = new HashMap<String, Object>();
        //设置变量 判断流程走向
        taskVariables.put("comment",comment);
        //?借款是否设置 ？
        taskService.complete(taskId, taskVariables);

        //判断 流程是否结束

        ProcessInstance pi =runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if(pi==null){
            logger.info("流程状态:-------------------------------流程结束");
            leaveService.updateResultByKey(comment,id);
        }else{
            logger.info("流程状态:---------------------------------流程正在进行");
        }
        return "process/complete-success";

    }
    @RequestMapping("/process/preview")
    public String  preview(
            @RequestParam("proid") String proid ,
            @RequestParam("busId") String busId,
            Model model , HttpSession session){
        //查询业务
        Leave leave = leaveService.selectByPrimaryKey(Integer.valueOf(busId));
        List<MyComment> historyCommnets = new ArrayList<MyComment>();

//       2）通过流程实例查询所有的(用户任务类型)历史活动
        List<HistoricActivityInstance> hais = historyService.createHistoricActivityInstanceQuery().processInstanceId(proid).activityType("userTask").list();
//       3）查询每个历史任务的批注
        if(hais!=null && hais.size()>=0){
            for (HistoricActivityInstance hai : hais) {
                String historytaskId = hai.getTaskId();
                List<Comment> comments = taskService.getTaskComments(historytaskId);
                // 4）如果当前任务有批注信息，添加到集合中
                if(comments!=null && comments.size()>0){
                    for(Comment c:comments){
                        MyComment  myComment =new MyComment();
                        myComment.setContent(c.getFullMessage());
                        myComment.setName(c.getUserId());
                        historyCommnets.add(myComment);
                    }

                }
            }

        }
        model.addAttribute("comments",historyCommnets);
        model.addAttribute("leave",leave);
        return  "process/leave-preview";
    }
}
